@using ThridGroup.ERP.Application.Contracts.DTO
@model OutgoingInspectionDto
@{
    ViewData["Title"] = Model.Id > 0 ? "修改出货检验单" : "新增出货检验单";
    Layout = null;
}

<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
    // 如果CDN加载失败，使用本地备用版本
    if (typeof jQuery === 'undefined') {
        document.write('<script src="~/libs/scripts/jquery/jquery-3.6.0.min.js"><\/script>');
    }
</script>
<style>
    body {
        background: #f5f5f5;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    }
    
    .edit-container {
        background: #fff;
        margin: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        overflow: hidden;
    }
    
    .edit-header {
        background: #fff;
        padding: 20px 30px;
        border-bottom: 1px solid #e8e8e8;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .edit-title {
        font-size: 18px;
        font-weight: 500;
        color: #333;
        margin: 0;
    }
    
    .close-btn {
        width: 24px;
        height: 24px;
        border: none;
        background: none;
        font-size: 16px;
        color: #999;
        cursor: pointer;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .close-btn:hover {
        background: #f5f5f5;
        color: #666;
    }
    
    .edit-content {
        padding: 30px;
    }
    
    .form-section {
        margin-bottom: 25px;
    }
    
    .layui-form-item {
        margin-bottom: 20px;
    }
    
    .layui-form-label {
        width: 100px;
        text-align: right;
        padding: 9px 15px 9px 0;
        color: #333;
        font-weight: normal;
    }
    
    .layui-form-label.required:before {
        content: '*';
        color: #ff5722;
        margin-right: 4px;
    }
    
    .layui-input-block {
        margin-left: 110px;
    }
    
    .auto-generate-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .layui-switch {
        margin-left: 10px;
    }
    
    .search-btn {
        margin-left: 10px;
        padding: 5px 15px;
        height: 32px;
        line-height: 22px;
    }
    
    .number-input-group {
        display: flex;
        align-items: center;
        width: 120px;
    }
    
    .number-btn {
        width: 30px;
        height: 38px;
        border: 1px solid #e6e6e6;
        background: #fafafa;
        color: #999;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        user-select: none;
    }
    
    .number-btn:hover {
        background: #f0f0f0;
        color: #666;
    }
    
    .number-btn.decrease {
        border-radius: 4px 0 0 4px;
        border-right: none;
    }
    
    .number-btn.increase {
        border-radius: 0 4px 4px 0;
        border-left: none;
    }
    
    .number-input {
        width: 60px;
        height: 38px;
        border: 1px solid #e6e6e6;
        border-left: none;
        border-right: none;
        text-align: center;
        padding: 0;
    }
    
    .statistics-section {
        border: 1px solid #e8e8e8;
        border-radius: 6px;
        margin: 25px 0;
    }
    
    .statistics-header {
        padding: 15px 20px;
        background: #fafafa;
        border-bottom: 1px solid #e8e8e8;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
    }
    
    .statistics-title {
        font-weight: 500;
        color: #333;
    }
    
    .collapse-icon {
        color: #999;
        transition: transform 0.3s;
    }
    
    .collapse-icon.expanded {
        transform: rotate(180deg);
    }
    
    .statistics-content {
        padding: 20px;
        display: none;
    }
    
    .statistics-content.show {
        display: block;
    }
    
    .statistics-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20px;
    }
    
    .stat-item {
        display: flex;
        flex-direction: column;
    }
    
    .stat-label {
        color: #666;
        font-size: 14px;
        margin-bottom: 5px;
    }
    
    .stat-input {
        height: 36px;
        border: 1px solid #e6e6e6;
        border-radius: 4px;
        padding: 0 12px;
        background: #f9f9f9;
        color: #999;
    }
    
    .inspection-section {
        margin-top: 25px;
    }
    
    .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e8e8e8;
    }
    
    .inspection-table {
        border: 1px solid #e8e8e8;
        border-radius: 6px;
        overflow: hidden;
    }
    
    .table-header {
        background: #fafafa;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
        gap: 1px;
        border-bottom: 1px solid #e8e8e8;
    }
    
    .table-cell {
        padding: 12px 15px;
        font-size: 14px;
        color: #333;
        background: #fafafa;
        text-align: center;
        font-weight: 500;
    }
    
    .table-row {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
        gap: 1px;
        border-bottom: 1px solid #f0f0f0;
        background: #f0f0f0;
    }
    
    .table-data {
        padding: 12px 15px;
        font-size: 14px;
        color: #333;
        background: #fff;
        text-align: center;
    }
    
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 20px 0;
        gap: 10px;
    }
    
    .form-actions {
        margin-top: 30px;
        padding-top: 20px;
        border-top: 1px solid #e8e8e8;
        text-align: center;
        gap: 15px;
        display: flex;
        justify-content: center;
    }
    
    .layui-btn {
        padding: 8px 25px;
        border-radius: 6px;
        font-weight: normal;
    }
    
    .input-group {
        display: flex;
        align-items: center;
        gap: 10px;
        flex: 1;
    }
    
    .full-width {
        width: 100%;
    }
</style>

<div class="edit-container">
    <!-- 头部 -->
    <div class="edit-header">
        <h3 class="edit-title">@ViewData["Title"]</h3>
        <button type="button" class="close-btn" onclick="closeWindow()">
            <i class="layui-icon layui-icon-close"></i>
        </button>
    </div>
    
    <!-- 内容 -->
    <div class="edit-content">
        <form class="layui-form" id="editForm" lay-filter="editForm">
            <input type="hidden" name="Id" value="@(Model?.Id ?? 0)" />
            @Html.AntiForgeryToken()
            
            <!-- 基本信息 -->
            <div class="form-section">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label required">检验单编号</label>
                            <div class="layui-input-block">
                                <div class="input-group">
                                    <input type="text" name="OutgoingCode" value="@(Model?.OutgoingCode ?? "")" 
                                           placeholder="请输入出货检验单编号" 
                                           autocomplete="off" 
                                           class="layui-input" 
                                           lay-verify="required" 
                                           lay-reqtext="出货检验单编号不能为空" />
                                    <div class="auto-generate-group">
                                        <input type="checkbox" name="autoGenerate" lay-skin="switch" lay-text="自动生成|手动输入" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label required">检验单名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="OutgoingName" value="@(Model?.OutgoingName ?? "")" 
                                       placeholder="请输入检验单名称" 
                                       autocomplete="off" 
                                       class="layui-input" 
                                       lay-verify="required" 
                                       lay-reqtext="检验单名称不能为空" />
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品编码</label>
                            <div class="layui-input-block">
                                <div class="input-group">
                                    <input type="text" name="ProductCode" value="@(Model?.ProductCode ?? "")" 
                                           placeholder="请输入产品编码" 
                                           autocomplete="off" 
                                           class="layui-input" />
                                    <button type="button" class="layui-btn layui-btn-primary search-btn" onclick="searchProduct()">
                                        <i class="layui-icon layui-icon-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="ProductName" value="@(Model?.ProductName ?? "")" 
                                       placeholder="请输入产品名称" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">单位</label>
                            <div class="layui-input-block">
                                <input type="text" name="Unitt" value="@(Model?.Unitt ?? "")" 
                                       placeholder="请输入单位" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">规格型号</label>
                            <div class="layui-input-block">
                                <input type="text" name="Specifications" value="@(Model?.Specifications ?? "")" 
                                       placeholder="请输入规格型号" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户编码</label>
                            <div class="layui-input-block">
                                <div class="input-group">
                                    <input type="text" name="CustomerCode" value="" 
                                           placeholder="请输入客户编码" 
                                           autocomplete="off" 
                                           class="layui-input" />
                                    <button type="button" class="layui-btn layui-btn-primary search-btn" onclick="searchCustomer()">
                                        <i class="layui-icon layui-icon-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="Customer" value="@(Model?.Customer ?? "")" 
                                       placeholder="请输入客户名称" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">批次号</label>
                            <div class="layui-input-block">
                                <input type="text" name="Batch" value="@(Model?.Batch ?? "")" 
                                       placeholder="请输入批次号" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 数量信息 -->
            <div class="form-section">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">发货数量</label>
                            <div class="layui-input-block">
                                <div class="number-input-group">
                                    <div class="number-btn decrease" onclick="adjustNumber('Send', -1)">
                                        <i class="layui-icon layui-icon-subtraction"></i>
                                    </div>
                                    <input type="number" name="Send" value="@(Model?.Send ?? 1)" 
                                           class="layui-input number-input" 
                                           min="0" />
                                    <div class="number-btn increase" onclick="adjustNumber('Send', 1)">
                                        <i class="layui-icon layui-icon-addition"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">检测数量</label>
                            <div class="layui-input-block">
                                <div class="number-input-group">
                                    <div class="number-btn decrease" onclick="adjustNumber('TestingNum', -1)">
                                        <i class="layui-icon layui-icon-subtraction"></i>
                                    </div>
                                    <input type="number" name="TestingNum" value="@(Model?.TestingNum ?? 1)" 
                                           class="layui-input number-input" 
                                           min="0" />
                                    <div class="number-btn increase" onclick="adjustNumber('TestingNum', 1)">
                                        <i class="layui-icon layui-icon-addition"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">不合格数量</label>
                            <div class="layui-input-block">
                                <div class="number-input-group">
                                    <div class="number-btn decrease" onclick="adjustNumber('UnqualifiedNum', -1)">
                                        <i class="layui-icon layui-icon-subtraction"></i>
                                    </div>
                                    <input type="number" name="UnqualifiedNum" value="@(Model?.UnqualifiedNum ?? 0)" 
                                           class="layui-input number-input" 
                                           min="0" />
                                    <div class="number-btn increase" onclick="adjustNumber('UnqualifiedNum', 1)">
                                        <i class="layui-icon layui-icon-addition"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 日期和检测信息 -->
            <div class="form-section">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">出货日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="ShipmentDate" id="shipmentDate" 
                                       value="@(Model?.ShipmentDate.ToString("yyyy-MM-dd") ?? "")" 
                                       placeholder="请选择出货日期" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">检测日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="TestingDate" id="testingDate" 
                                       value="@(Model?.TestingDate.ToString("yyyy-MM-dd") ?? "")" 
                                       placeholder="请选择检测日期" 
                                       autocomplete="off" 
                                       class="layui-input" />
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">检测结果</label>
                            <div class="layui-input-block">
                                <select name="TestingResult" lay-filter="testingResult">
                                    <option value="">请选择检测结果</option>
                                    <option value="合格" selected="@(Model?.TestingResult == "合格")">合格</option>
                                    <option value="不合格" selected="@(Model?.TestingResult == "不合格")">不合格</option>
                                    <option value="待检验" selected="@(Model?.TestingResult == "待检验")">待检验</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 暂时注释掉备注字段，待数据库字段添加后启用
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-form-item">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <textarea name="Remarks" placeholder="请输入备注" 
                                          class="layui-textarea" 
                                          rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                -->
            </div>
            
            <!-- 反馈明细 -->
            <div class="statistics-section">
                <div class="statistics-header" onclick="toggleStatistics()">
                    <span class="statistics-title">反馈明细</span>
                    <i class="layui-icon layui-icon-down collapse-icon"></i>
                </div>
                <div class="statistics-content" id="statisticsContent">
                    <div class="statistics-grid">
                        <div class="stat-item">
                            <label class="stat-label">合格率</label>
                            <input type="text" class="stat-input" value="95%" readonly />
                        </div>
                        <div class="stat-item">
                            <label class="stat-label">不合格率</label>
                            <input type="text" class="stat-input" value="5%" readonly />
                        </div>
                        <div class="stat-item">
                            <label class="stat-label">检测人员</label>
                            <input type="text" name="TestingPerson" value="@(Model?.TestingPerson ?? "")" 
                                   placeholder="请输入检测人员" 
                                   class="layui-input" />
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="form-actions">
                <button type="button" class="layui-btn layui-btn-normal" id="saveBtn">
                    <i class="layui-icon layui-icon-ok"></i> 保存
                </button>
                @if (Model != null && Model.Id > 0 && Model.State == 0)
                {
                    <button type="button" class="layui-btn layui-btn-warm" id="completeBtn">
                        <i class="layui-icon layui-icon-ok-circle"></i> 完成检验
                    </button>
                }
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeWindow()">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </form>
    </div>

</div>

<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    // 页面加载完成后执行
    $(document).ready(function() {
        console.log('页面加载完成');
        
        // 初始化Layui组件
        layui.use(['layer', 'form', 'laydate'], function(){
            var layer = layui.layer;
            var form = layui.form;
            var laydate = layui.laydate;
            
            console.log('Layui组件已加载');
            
            // 初始化日期选择器
            laydate.render({
                elem: '#shipmentDate',
                type: 'date',
                format: 'yyyy-MM-dd'
            });
            
            laydate.render({
                elem: '#testingDate',
                type: 'date',
                format: 'yyyy-MM-dd'
            });
            
            // 渲染表单
            form.render();
            
            // 自动初始化日期字段
            if (!$('#shipmentDate').val()) {
                $('#shipmentDate').val(formatDate(new Date()));
            }
            
            if (!$('#testingDate').val()) {
                $('#testingDate').val(formatDate(new Date()));
            }
            
            console.log('日期控件已初始化');
            
            // 绑定保存按钮事件
            $('#saveBtn').click(function() {
                console.log('保存按钮被点击');
                saveData(0);
            });
            
            // 绑定完成检验按钮事件
            $('#completeBtn').click(function() {
                console.log('完成检验按钮被点击');
                saveData(1);
            });
            
            // 提交表单处理 - 移入layui.use作用域内
            form.on('submit(submitForm)', function(data) {
                var field = data.field;
                
                // 确保数值类型正确
                field.id = parseInt(field.id || '0');
                field.send = parseInt(field.send || '0');
                field.testingNum = parseInt(field.testingNum || '0');
                field.unqualifiedNum = parseInt(field.unqualifiedNum || '0');
                field.state = parseInt(field.state || '0');
                
                // 转换日期字符串为ISO日期格式
                if (field.shipmentDate) {
                    field.shipmentDate = formatDateToServer(field.shipmentDate);
                }
                if (field.testingDate) {
                    field.testingDate = formatDateToServer(field.testingDate);
                }

                console.log('提交的表单数据:', field);
                
                var url = field.id > 0 ? '/ProductionSystem/OutgoingInspection/Update' : '/ProductionSystem/OutgoingInspection/Add';
                
                // 显示加载层
                var loadingLayer = layer.load(1, {
                    shade: [0.1, '#fff']
                });
                
                $.ajax({
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(field),
                    success: function(res) {
                        layer.close(loadingLayer);
                        if (res.code === 0) {
                            layer.msg('保存成功', {
                                icon: 1,
                                time: 1500
                            }, function() {
                                // 关闭当前页面并刷新父页面表格
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.layui.table.reload('outgoingTable');
                            });
                        } else {
                            layer.msg('保存失败: ' + (res.msg || '未知错误'), {
                                icon: 2,
                                time: 3000
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadingLayer);
                        console.error('提交失败:', xhr.responseText);
                        
                        var errorMessage = '提交失败';
                        try {
                            var errorResponse = JSON.parse(xhr.responseText);
                            errorMessage = errorResponse.msg || error || '服务器错误';
                        } catch (e) {
                            errorMessage = error || '网络错误，请稍后重试';
                        }
                        
                        layer.msg('保存失败: ' + errorMessage, {
                            icon: 2,
                            time: 3000
                        });
                    }
                });
                
                return false; // 阻止默认表单提交
            });
        });
        
        // 计算初始统计数据
        calculateStatistics();
    });
    
    // 格式化日期为yyyy-MM-dd
    function formatDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        return year + '-' + month + '-' + day;
    }
    
    // 格式化日期为服务端格式
    function formatDateToServer(dateStr) {
        try {
            var parts = dateStr.split('-');
            if (parts.length === 3) {
                // 确保年月日格式正确
                return parts[0] + '-' + parts[1] + '-' + parts[2];
            }
            return dateStr;
        } catch (e) {
            console.error('日期格式转换错误', e);
            return dateStr;
        }
    }
    
    // 保存数据函数
    function saveData(state) {
        // 获取表单数据
        var formData = {};
        var form = $('#editForm');
        
        // 手动收集表单字段
        formData.Id = parseInt($('input[name="Id"]').val() || 0);
        formData.OutgoingCode = $('input[name="OutgoingCode"]').val();
        formData.OutgoingName = $('input[name="OutgoingName"]').val();
        formData.ProductCode = $('input[name="ProductCode"]').val();
        formData.ProductName = $('input[name="ProductName"]').val();
        formData.Unitt = $('input[name="Unitt"]').val();
        formData.Specifications = $('input[name="Specifications"]').val();
        formData.Customer = $('input[name="Customer"]').val();
        formData.Batch = $('input[name="Batch"]').val();
        formData.Send = parseInt($('input[name="Send"]').val() || 0);
        formData.TestingNum = parseInt($('input[name="TestingNum"]').val() || 0);
        formData.UnqualifiedNum = parseInt($('input[name="UnqualifiedNum"]').val() || 0);
        
        // 处理日期格式
        var shipmentDateStr = $('input[name="ShipmentDate"]').val();
        var testingDateStr = $('input[name="TestingDate"]').val();
        
        // 确保日期格式正确 (yyyy-MM-dd)
        if (shipmentDateStr) {
            try {
                var shipmentDate = new Date(shipmentDateStr);
                if (!isNaN(shipmentDate.getTime())) {
                    formData.ShipmentDate = shipmentDate.toISOString().split('T')[0];
                } else {
                    formData.ShipmentDate = new Date().toISOString().split('T')[0];
                }
            } catch (e) {
                console.error('日期格式化错误:', e);
                formData.ShipmentDate = new Date().toISOString().split('T')[0];
            }
        } else {
            formData.ShipmentDate = new Date().toISOString().split('T')[0];
        }
        
        if (testingDateStr) {
            try {
                var testingDate = new Date(testingDateStr);
                if (!isNaN(testingDate.getTime())) {
                    formData.TestingDate = testingDate.toISOString().split('T')[0];
                } else {
                    formData.TestingDate = new Date().toISOString().split('T')[0];
                }
            } catch (e) {
                console.error('日期格式化错误:', e);
                formData.TestingDate = new Date().toISOString().split('T')[0];
            }
        } else {
            formData.TestingDate = new Date().toISOString().split('T')[0];
        }
        
        console.log('原始出货日期:', shipmentDateStr, '处理后:', formData.ShipmentDate);
        console.log('原始检测日期:', testingDateStr, '处理后:', formData.TestingDate);
        
        formData.TestingResult = $('select[name="TestingResult"]').val();
        formData.TestingPerson = $('input[name="TestingPerson"]').val();
        formData.State = state;
        
        // 验证必填字段
        if (!formData.OutgoingCode) {
            layui.layer.msg('出货检验单编号不能为空！', {icon: 2});
            return;
        }
        
        if (!formData.OutgoingName) {
            layui.layer.msg('检验单名称不能为空！', {icon: 2});
            return;
        }
        
        // 显示加载提示
        var loading = layui.layer.load(2, {shade: [0.3, '#fff']});
        
        // 获取防伪令牌
        var token = $('input[name="__RequestVerificationToken"]').val();
        
        // 判断是添加还是更新操作
        var isUpdate = formData.Id > 0;
        var url = isUpdate ? 
            '/ProductionSystem/OutgoingInspection/Update' : 
            '/ProductionSystem/OutgoingInspection/Add';
        
        console.log('操作类型:', isUpdate ? '更新' : '添加');
        console.log('ID值:', formData.Id);
        console.log('请求URL:', url);
        
        // 对于添加操作，确保设置默认值
        if (!isUpdate) {
            // 设置Id为0，确保后端知道这是新增
            formData.Id = 0;
            
            // 如果缺少检测结果，设置默认值
            if (!formData.TestingResult) {
                formData.TestingResult = '待检验';
            }
            
            // 如果缺少状态，默认为0（未完成）
            formData.State = formData.State || 0;
            
            // 确保其他必填字段有值
            if (!formData.TestingPerson) {
                formData.TestingPerson = '未指定';
            }
            
            // 检查数量字段
            if (formData.Send <= 0) {
                formData.Send = 1;
            }
            
            if (formData.TestingNum <= 0) {
                formData.TestingNum = 1;
            }
        }
        
        console.log('处理后的提交数据:', formData);
        
        // 发送请求
        $.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers: {
                'RequestVerificationToken': token
            },
            success: function(res) {
                layui.layer.close(loading);
                console.log('服务器响应:', res);
                
                if (res && res.code === 0) {
                    layui.layer.msg((isUpdate ? '更新' : '添加') + '成功！', {icon: 1, time: 1500}, function() {
                        // 关闭当前页面并刷新父页面表格
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                        parent.layui.table.reload('outgoingTable');
                    });
                } else {
                    layui.layer.msg(res.msg || ((isUpdate ? '更新' : '添加') + '失败'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layui.layer.close(loading);
                console.error('请求失败:', status, error);
                console.error('响应文本:', xhr.responseText);
                
                var errorMessage = '请求失败';
                try {
                    if (xhr.responseText) {
                        var errorResponse = JSON.parse(xhr.responseText);
                        errorMessage = errorResponse.msg || errorResponse.message || errorMessage;
                    }
                } catch (e) {
                    console.error('解析错误响应失败:', e);
                }
                
                layui.layer.msg(errorMessage, {icon: 2});
            }
        });
    }
    
    // 关闭窗口
    function closeWindow() {
        if (parent.layer) {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        } else {
            window.close();
        }
    }
    
    // 数量调节
    function adjustNumber(fieldName, delta) {
        var input = document.querySelector('input[name="' + fieldName + '"]');
        var currentValue = parseInt(input.value) || 0;
        var newValue = Math.max(0, currentValue + delta);
        
        // 数量验证逻辑
        if (fieldName === 'TestingNum') {
            var sendValue = parseInt(document.querySelector('input[name="Send"]').value) || 0;
            if (newValue > sendValue) {
                if (typeof layui !== 'undefined' && layui.layer) {
                    layui.layer.msg('检测数量不能大于发货数量！');
                } else {
                    alert('检测数量不能大于发货数量！');
                }
                return;
            }
        }
        
        if (fieldName === 'UnqualifiedNum') {
            var testingValue = parseInt(document.querySelector('input[name="TestingNum"]').value) || 0;
            if (newValue > testingValue) {
                if (typeof layui !== 'undefined' && layui.layer) {
                    layui.layer.msg('不合格数量不能大于检测数量！');
                } else {
                    alert('不合格数量不能大于检测数量！');
                }
                return;
            }
        }
        
        input.value = newValue;
        
        // 实时计算合格率和不合格率
        calculateStatistics();
    }
    
    // 实时计算统计数据
    function calculateStatistics() {
        var testingNum = parseInt(document.querySelector('input[name="TestingNum"]').value) || 0;
        var unqualifiedNum = parseInt(document.querySelector('input[name="UnqualifiedNum"]').value) || 0;
        
        if (testingNum > 0) {
            var qualifiedNum = testingNum - unqualifiedNum;
            var qualifiedRate = ((qualifiedNum / testingNum) * 100).toFixed(1);
            var unqualifiedRate = ((unqualifiedNum / testingNum) * 100).toFixed(1);
            
            // 更新统计显示
            var qualifiedRateInput = document.querySelector('.statistics-grid .stat-item:nth-child(1) input');
            var unqualifiedRateInput = document.querySelector('.statistics-grid .stat-item:nth-child(2) input');
            
            if (qualifiedRateInput) qualifiedRateInput.value = qualifiedRate + '%';
            if (unqualifiedRateInput) unqualifiedRateInput.value = unqualifiedRate + '%';
            
            // 根据合格率自动设置检测结果
            var testingResultSelect = document.querySelector('select[name="TestingResult"]');
            if (testingResultSelect && !testingResultSelect.value) {
                if (unqualifiedNum === 0) {
                    testingResultSelect.value = '合格';
                } else if (qualifiedRate >= 80) {
                    testingResultSelect.value = '合格';
                } else {
                    testingResultSelect.value = '不合格';
                }
                // 重新渲染select
                if (typeof layui !== 'undefined' && layui.form) {
                    layui.form.render('select');
                }
            }
        }
    }
    
    // 切换统计信息显示
    function toggleStatistics() {
        var content = document.getElementById('statisticsContent');
        var icon = document.querySelector('.collapse-icon');
        
        if (content.classList.contains('show')) {
            content.classList.remove('show');
            icon.classList.remove('expanded');
        } else {
            content.classList.add('show');
            icon.classList.add('expanded');
        }
    }
    
    // 自动生成检验单编号
    document.querySelector('input[name="autoGenerate"]').addEventListener('change', function() {
        var codeInput = document.querySelector('input[name="OutgoingCode"]');
        if (this.checked) {
            // 编辑模式下，如果已有编号，询问是否覆盖
            var hasExistingCode = codeInput.value && codeInput.value.trim() !== '';
            
            @{
                var jsIsEditMode = Model != null && Model.Id > 0;
            }
            var isEditMode = @Html.Raw(jsIsEditMode.ToString().ToLower());
            
            if (isEditMode && hasExistingCode) {
                layer.confirm('当前已有检验单编号，是否重新生成？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    generateNewCode(codeInput);
                    layer.close(index);
                }, function(index) {
                    // 取消时恢复开关状态
                    document.querySelector('input[name="autoGenerate"]').checked = false;
                    layui.form.render();
                    layer.close(index);
                });
            } else {
                generateNewCode(codeInput);
            }
        } else {
            codeInput.readOnly = false;
        }
    });
    
    // 生成新编号的函数
    function generateNewCode(codeInput) {
        // 生成格式：OQC + 年月日 + 4位序号
        var now = new Date();
        var dateStr = now.getFullYear().toString() + 
                     (now.getMonth() + 1).toString().padStart(2, '0') + 
                     now.getDate().toString().padStart(2, '0');
        var randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        codeInput.value = 'OQC' + dateStr + randomNum;
        codeInput.readOnly = true;
    }
    
    // 初始化自动生成状态
    document.addEventListener('DOMContentLoaded', function() {
        var autoGenerate = document.querySelector('input[name="autoGenerate"]');
        var codeInput = document.querySelector('input[name="OutgoingCode"]');
        
        @{
            var initIsEditMode = Model != null && Model.Id > 0;
            var initHasCode = !string.IsNullOrEmpty(Model?.OutgoingCode);
        }
        
        var isEditModeInit = @Html.Raw(initIsEditMode.ToString().ToLower());
        var hasCodeInit = @Html.Raw(initHasCode.ToString().ToLower());
        
        // 如果是新增模式且没有编号，自动生成
        if (!isEditModeInit && !hasCodeInit) {
            autoGenerate.checked = true;
            layui.form.render();
            generateNewCode(codeInput);
        }
        
        // 如果是编辑模式且有编号，禁用自动生成开关
        if (isEditModeInit && hasCodeInit) {
            codeInput.readOnly = true;
        }
        
        // 初始化计算
        setTimeout(function() {
            calculateStatistics();
        }, 100);
    });
    
    // 搜索产品
    function searchProduct() {
        layer.open({
            type: 2,
            title: '选择产品',
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '600px'],
            content: '/ProductionSystem/Product/SelectDialog',
            success: function(layero, index) {
                // 可以在这里设置回调函数
            },
            end: function() {
                // 可以在这里处理选择结果
            }
        });
    }
    
    // 搜索客户
    function searchCustomer() {
        layer.open({
            type: 2,
            title: '选择客户',
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '600px'],
            content: '/Customer/SelectDialog',
            success: function(layero, index) {
                // 可以在这里设置回调函数
            },
            end: function() {
                // 可以在这里处理选择结果
            }
        });
    }
</script> 